
import express from 'express';
import axios from 'axios';
import cors from 'cors';
const app=express();
const port=3000;
app.use(cors());
app.use(express.json());
const API_KEY = 'bce-v3/ALTAK-zVxB7BFMqIVZRtCQFfEQL/1579b41d79e97207d7018601a8a9cb8ec2a03130';
const SECRET_KEY = 'e337432ba1074ec5a6a0a9d195ba7206';

const getAccessToken=async()=>{
    const response=await axios.post('https://aip.baidubce.com/oauth/2.0/token',null,{
        params:{
      client_id: API_KEY,
      client_secret: SECRET_KEY,
      grant_type: 'client_credentials'
        }
    });
    return response.data.access_token;
};
app.post('/api/search',async(req,res)=>{
    const {keyword}=req.body;
    if(!keyword){
        return res.status(400).json(['请输入关键词']);
    }
     try{
        const access_token=await getAccessToken();
        const response=await axios.post(
           `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=${access_token}`,
           {
            message:[
                {
                    role:'user',
                    content:keyword
                }
            ]
           }
        );
        res.json(response.data.result);
     }catch(error){
        console.error('调用百度千帆大模型失败',error);
        res.status(500).json(['搜索失败，稍后重试']);
     }
     
});
app.listen(port,()=>{
    console.log(`Server running at http://localhost:${port}`)
})
